/* chat_b.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/wait.h>   /* 新增：声明 wait */

#define FIFO_A2B "fifo1"
#define FIFO_B2A "fifo2"

static int open_fifo(const char *path, int flags)
{
    if (access(path, F_OK) == -1 && mkfifo(path, 0666) == -1 && errno != EEXIST) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }
    int fd = open(path, flags);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }
    return fd;
}

int main(void)
{
    int fd_read  = open_fifo(FIFO_A2B, O_RDONLY);  /* 读自 A */
    int fd_write = open_fifo(FIFO_B2A, O_WRONLY);  /* 写向 A */

    puts("[B] 已连接，开始聊天（输入 exit 退出）：");

    pid_t pid = fork();
    if (pid == 0) {                    /* 子进程：负责读 */
        char buf[1024];
        while (1) {
            ssize_t n = read(fd_read, buf, sizeof(buf) - 1);
            if (n <= 0) break;
            buf[n] = '\0';
            if (strncmp(buf, "exit", 4) == 0) break;
            printf("[A] %s", buf);
        }
        close(fd_read);
        exit(0);
    } else if (pid > 0) {              /* 父进程：负责写 */
        char buf[1024];
        while (fgets(buf, sizeof(buf), stdin)) {
            write(fd_write, buf, strlen(buf));
            if (strcmp(buf, "exit\n") == 0) break;
        }
        close(fd_write);
        wait(NULL);
    }

    unlink(FIFO_A2B);
    unlink(FIFO_B2A);
    return 0;
}